#coding=utf-8
#LightCam 交易日历生成程序
#init by hfh 20150727

import cx_Oracle,base64,time,sys,subprocess,os
import lc_libs

def scpfile():
	
	#copy file from ywn_monitor1 to mondb1
	scpcomd="scp %s mondb1:%s" % (hcfilename,hcfilename)
	#popen=subprocess.Popen(scpcomd,stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True)
	os.system(scpcomd)
	
	#copy file from mondb1 to all 
	
	#WGQ
	scpcomd='ssh mondb1 "cd /monitor/tools;sh PutFile.sh list.lc %s lc_holiday.conf %s/conf/"' % (hcfilename,lchome)
	
	#ZJ
	if location == "ZJ":
		scpcomd='ssh mondb1 "cd /monitor/imonitor/tools;sh PutFile.sh list.lc %s lc_holiday.conf %s/conf/"' % hcfilename
	
	#popen=subprocess.Popen(scpcomd,stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True)
	os.system(scpcomd)
	

if __name__ == "__main__":

	lchome=lc_libs.lc_getlchome()
	scname=sys.argv[0].split('.')[0]
	logfilename=lchome+'/log/'+scname+'.log'
	confname=lchome+'/conf/'+scname+'.conf'

	today=time.strftime('%Y%m%d',time.localtime())
	os.system("mv %s %s.%s" % (logfilename,logfilename,today))
	
	logfile=file(logfilename,'a')
	logdate=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
	logfile.write(logdate+" Started.\n")
	logfile.flush()
	
	hcfilename=lchome+"/conf/lc_holiday.conf"
	agent_hostname=lc_libs.lc_gethostname()
	
	location="WGQ"
	dbname="orabiz"
	username="cffex"
	#WGQ
	passwd="Yml6X3Bhc3NfMDkwOA=="
	#ZJ
	#passwd="Yml6X3B3ZF8wNTIy\n"

	for line in open(confname):
		if line[0] == '#':
			continue
		else:
			lines=line.strip('\n').split("\t")
			if len(lines)<5 or lines[0] not in (agent_hostname,'default'):
				continue
			else:
				location=lines[1]
				dbname=lines[2]
				username=lines[3]
				passwd=lines[4]
		
	
	schedule='0-6,00:30-00:31'
	while True:
		time.sleep(1)
		
		try:
			time_state = lc_libs.lc_schedule(schedule)
			if time_state == False:
				continue

			con=cx_Oracle.connect("%s/%s@%s" % (username,base64.decodestring(passwd),dbname))
			cur=con.cursor()
			res=cur.execute("select YEAR,MONTH,DAY from exchangeadmin.t_calendar where TRA=0 and SUN=0 and SAT=0 order by 1,2,3")
			
			holidays="#holidays\n"
			for YEAR,MONTH,DAY in res.fetchall():
				if int(MONTH)<10:
					MONTH="0"+str(MONTH)
				if int(DAY)<10:
					DAY="0"+str(DAY)
				if str(YEAR) == str(time.strftime('%Y',time.localtime())):
					holidays += "%4s-%2s-%2s\n" % (YEAR,MONTH,DAY)
			print holidays
			curfile=open(hcfilename,'r')
			cur=curfile.read()
			curfile.close()
			if cur != holidays:
				upd=open(hcfilename,'w')
				upd.write(holidays)
				upd.close()
				logdate=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
				logfile.write(logdate+" Update Holiday ConfFile.\n")
				logfile.flush()
				scpfile()
			time.sleep(82800)
			
		except Exception:
			excinfo=traceback.format_exc()
			logdate=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
			logfile.write(logdate+" :\n"+excinfo+"\n")
			logfile.flush()
		time.sleep(30)
